package one_many

import (
	"fmt"
	"sync"
	"time"
)

type Task struct {
	ID int64
}

// 任务
func (t *Task) run() {
	//out.Println(t.ID)
	fmt.Println("执行任务:", t.ID)
}

var taskCh = make(chan Task, 10)

const taskNum int64 = 1000

func producer(wo chan<- Task) {
	var i int64
	for i = 1; i <= taskNum; i++ {
		t := Task{
			ID: i,
		}
		wo <- t
		fmt.Println("生产:", t)
	}
	close(wo)
}

func comsumer(ro <-chan Task) {
	for t := range ro {
		t.run()
	}
}

func Exe() {
	wg := &sync.WaitGroup{}
	wg.Add(1)
	go func(wg *sync.WaitGroup) {
		defer wg.Done()
		producer(taskCh)

	}(wg)
	for i := 0; i < int(taskNum); i++ {
		if i%100 == 0 {
			wg.Add(1)
			fmt.Println("添加消费者")
			time.Sleep(time.Second)
			go func(wg *sync.WaitGroup) {
				defer wg.Done()
				comsumer(taskCh)

			}(wg)
		}

	}

	wg.Wait()
	fmt.Println("安全退出了...")
}
